<template>
  <div>
    <div ref="lineChartRef" class="lineChart"></div>
    <div ref="pieChartRef" class="pieChart"></div>
    <div style="position:absolute;top:100px;left: 80px;">
      <label>开始日期 <input type="date" v-model="start_date" value="{{ getCurrentDate() }}"></label>
    </div>
    <div style="position:absolute;top:100px;left: 280px;">
      <label>结束日期 <input type="date" v-model="end_date" value="{{ getCurrentDate() }}"></label>
    </div>
    <button @click="getInfo()" style="position:absolute;top:102px;left: 475px;"> 查询 </button>
  </div>
</template>
<script setup>
import axios from 'axios';
import {nextTick, onMounted, onUnmounted, ref} from 'vue';
import * as echarts from 'echarts';
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;

const lineChartRef = ref(null);
const pieChartRef = ref(null);
let lineChart, pieChart;

const start_date = ref('');
const end_date = ref('');
const roomDetails = ref({});

// 初始化图表
function initCharts() {
  lineChart = echarts.init(lineChartRef.value);
  pieChart = echarts.init(pieChartRef.value);
}

onMounted(async () => {
  start_date.value = getCurrentDate();
  end_date.value = getCurrentDate();
  await nextTick();
  initCharts();  // 初始化图表
  await getInfo();     // 加载并渲染数据

  window.addEventListener('resize', () => {
    lineChart.resize();
    pieChart.resize();
  });

  // 设置折线图的点击事件
  lineChart.on('click', function (params) {
    if (params.componentType === 'series') {
      const roomData = roomDetails.value[params.dataIndex+1];
      console.log(roomData)
      updatePieChart(roomData, params.name);  // params.name 是被点击的房间号
    }
  });
});

onUnmounted(() => {
  window.removeEventListener('resize', () => {
    lineChart.resize();
    pieChart.resize();
  });
});

async function getInfo() {
  try {
    const params = {
      start_date: start_date.value,
      end_date: end_date.value
    };
    const response = await axios.get(`${apiBaseUrl}/manager`, { params });
    if (response.data) {
      console.log(response.data);
      roomDetails.value = response.data;  // 假设 response.data 是房间数据数组
      lineChart.setOption(generateLineOptions(roomDetails.value));
    }
  } catch (error) {
    console.error("Error fetching data:", error);
    alert('无法加载数据，请检查服务器状态！');
  }
}



function generateLineOptions(data) {
  return {
    legend: {},
    tooltip: {},
    dataset: {
      source: data
    },
    // 声明一个 X 轴，类目轴（category）。默认情况下，类目轴对应到 dataset 第一列。
    xAxis: { type: 'category' },
    // 声明一个 Y 轴，数值轴。
    yAxis: {},
    // 声明多个 bar 系列，默认情况下，每个系列会自动对应到 dataset 的每一列。
    series: [{ type: 'line' }, { type: 'line' }, { type: 'line' },{ type: 'line' },
      { type: 'line' }, { type: 'line' },{ type: 'line' }]
  };
}

function updatePieChart(roomData, roomNumber) {
  const pieData = [
    {value: roomData[4], name: '调度次数'},
    {value: roomData[5], name: '详单条数'},
    {value: roomData[6], name: '开关次数'},
    {value: roomData[7], name: '调温次数'},
    {value: roomData[8], name: '调风次数'},
  ];

  pieChart.setOption({
    title: {
      text: `房间${roomNumber} 的详细统计`,
      left: 'center',
      textStyle: {
        color: 'black',
        fontWeight: 'bold'
      }
    },
    series: [
      {
        name: '操作详情',
        type: 'pie',
        radius: ['0%', '40%'],
        data: pieData,
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)',  // {b}是数据项名称，{c}是数值，{d}是百分比
          position: 'outside',
          textStyle: {
            color: 'black',
            fontWeight: 'bold',
            fontSize: 14
          }
        },
        labelLine: {
          show: true,  // 显示连接线
          length: 10,  // 连接线长度
          length2: 10, // 第二段连接线长度
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
}


function getCurrentDate() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
</script>
<style scoped>
.lineChart, .pieChart {
  position: absolute;
  height: 400px;

}
.lineChart {
  width: 850px;
  left: 30px;
  top:150px
}
.pieChart {
  right: 0;
  width: 500px;
  top:120px
}
</style>